/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bittorent.like;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.SimpleFormatter;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
/**
 *
 * @author tuongvanthanh
 */
public class Mainform extends javax.swing.JFrame {
    
    Logger logger=Logger.getLogger("Bittorent_Like_Log");
    FileHandler fh;
    String torrentName;
    
    


    /**
     * Creates new form Mainform
     */
    private ArrayList<String> hashes;
    
    
    
    public Mainform() {
        initComponents();
        try{
            DateFormat dfm=new SimpleDateFormat("yyyy-MM-dd-HHmmss");
            Date d=new Date();
            
            String path=new File(".").getCanonicalPath()+"\\Log\\bitlog"+dfm.format(d).toString().trim()+".log";
            
            fh=new FileHandler(path);
            logger.addHandler(fh);
            SimpleFormatter fmatter=new SimpleFormatter();
            fh.setFormatter(fmatter);
            logger.info("Init application program");
        }catch(SecurityException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
     private void OpenFile(){
        jFileChooser1.showOpenDialog(null);
        File f=jFileChooser1.getSelectedFile();
        jtfDuongDanFile.setText(jFileChooser1.getSelectedFile().getAbsolutePath());
        
        //int size=(int)f.length();
        //jlbKichThuocFile.setText(String.valueOf(size));
         
    }
      private void WriteChunkToDestination(byte[] temp, String destinationDriectory){
         try{
             OutputStream oStream=null;
             try{
                 oStream=new BufferedOutputStream(new FileOutputStream(destinationDriectory));
                 oStream.write(temp);
                 System.out.println("Ghi xuong thanh cong! ");
             }finally{
                 // dong luong ghi file xuong
                 oStream.close();
             }
         }catch(FileNotFoundException ex){
             ex.printStackTrace();
         }catch(IOException ex){
             ex.printStackTrace();
         }
     }
      private void readAndFragment(String sourcefilename, int CHUNK_SIZE){
         // lay file tu duong dan sourcefilename
        File willberead=new File(sourcefilename);
        // tinh kich thuoc file
        int FILE_SIZE=(int) willberead.length();
        // gan kich thuoc file cho nhan 'kich thuoc file'
        //jlbKichThuocFile.setText(String.valueOf(FILE_SIZE));
        // so luong chunk
        int NUMBER_OF_CHUNKS =0;
        // mang byte tam, dung de luu cac phan (chunk) cua mot file
        byte[] temporary=null;
        ArrayList<String> lsthash=new ArrayList<>();
        
        // create folder 
        File file=new File("."+"\\chunks");
        if(!file.exists()){
            file.mkdir();
        }
        // Dung ham de hash chunk
        MessageDigest md=null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        try{
            // khai bao mot luong de doc file tu sourcefilename
            InputStream inStream=null;
            // tong kich thuoc cua mot file
            int totalBytesRead=0;
            try{
                inStream=new BufferedInputStream(new FileInputStream(willberead));
                // khi chua doc het file
                while(totalBytesRead<FILE_SIZE){
                    // tao ten chunk
                    String PART_NAME="data"+NUMBER_OF_CHUNKS+".bin";
                    // tinh so byte con lai cua file dang doc
                    int bytesRemaining =FILE_SIZE-totalBytesRead;
                    // neu so byte con lai nho hon kich thuoc cua mot chunk ...
                    if(bytesRemaining<CHUNK_SIZE){
                        // thi kich thuoc cua chunk se duoc gan bang kich thuoc cua so byte con lai
                        CHUNK_SIZE=bytesRemaining; 
                        System.out.println("Chunk size:"+CHUNK_SIZE);
                    }
                    // bat dau doc file
                    // khoi tao mang temporary = kich thuoc chunk
                    temporary=new byte[CHUNK_SIZE];
                    // doc file vao mang tam temporary va lay kich thuoc doc duoc (bytes)
                    int bytesRead=inStream.read(temporary,0,CHUNK_SIZE);
                    // neu nhu chac chan doc duoc file bytesRead >0
                    if(bytesRead>0){
                        // thi se gan tong so byte doc duoc (totalBytesRead) cong them so byte vua doc duco(bytesRead)
                        totalBytesRead+=bytesRead;
                        // va tang so luong chunk len 1
                        NUMBER_OF_CHUNKS++; 
                    }
                    // luu file chunk xuong duong dan thu muc (jtfPathLuuChunk.gettext())
                    WriteChunkToDestination(temporary,file.getCanonicalPath()+"\\"+ PART_NAME);
                    // kiem tra ket qua man hinh console
                    System.out.println("Total bytes read: "+totalBytesRead);  
                    //System.out.println("Hashvalue:"+hashMD5(temporary));
                    //lsthash.add(hashMD5(temporary));
              
                        // dung ham de hash mang byte chunk
                        String hash=(new HexBinaryAdapter()).marshal(md.digest(temporary));
                        System.out.println("Hashvalue:"+hash);
                        lsthash.add(hash);
                   
                    
                }// end while
                // ghi file .torrent
                if(lsthash.size()>0){
                    String fname=willberead.getName();
                    if(fname.indexOf(".")>0){
                        
                        fname=fname.substring(0, fname.lastIndexOf("."));
                    }
                    torrentName=file.getCanonicalPath()+"\\"+fname+".torrent";
                    File fwrite=new File(file.getCanonicalPath()+"\\"+fname+".torrent");
                    if(!fwrite.exists()){
                        fwrite.createNewFile();           
                    }
                    FileWriter fw=new FileWriter(fwrite.getAbsoluteFile());
                    BufferedWriter bw=new BufferedWriter(fw);
                    for(int i=0;i<lsthash.size();i++){
                        bw.write(lsthash.get(i));
                        bw.write("\n");
                    }
                    bw.close();
                }
            } finally{
                // dong luong ghi file
                inStream.close();
            }
           
        }catch(FileNotFoundException ex){
            ex.printStackTrace();
        }catch(IOException ex){
            ex.printStackTrace();
        }
        //jlbSoLuongChunk.setText(String.valueOf(NUMBER_OF_CHUNKS));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        jFileChooser1 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jtfDuongDanFileTorrent = new javax.swing.JTextField();
        jbtMoFile = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jlbSoLuongChunk = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jlbChunkDangTai = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jlbSoChunkHoanTat = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jpsbarTrangThai = new javax.swing.JProgressBar();
        jbtMoFileHoanTat = new javax.swing.JButton();
        jbtThoat = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jbtnChiaSeChunk = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jtfDuongDanFileChunk = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jtfDuongDanFile = new javax.swing.JTextField();
        jbtDuyetFileChiaSe = new javax.swing.JButton();
        jtfPortFile = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem6 = new javax.swing.JMenuItem();

        jMenuItem1.setText("jMenuItem1");

        jMenu1.setText("jMenu1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bittorent-like 1.0");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Torrent file"));

        jLabel1.setText("Mở file .torrent :");

        jtfDuongDanFileTorrent.setEnabled(false);

        jbtMoFile.setText("Mở ...");
        jbtMoFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtMoFileActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Thông tin tải file"));

        jLabel3.setText("Số lượng chunk :");

        jlbSoLuongChunk.setText("sl");

        jLabel5.setText("Chunk đang tải :");

        jlbChunkDangTai.setText("cur chunk");

        jLabel7.setText("Hoàn tất :");

        jlbSoChunkHoanTat.setText("numb");

        jLabel9.setText("chunk");

        jButton1.setText("Bắt đầu tải...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(jlbSoLuongChunk))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel7))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbSoChunkHoanTat)
                            .addComponent(jlbChunkDangTai))
                        .addGap(5, 5, 5)
                        .addComponent(jLabel9)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addComponent(jpsbarTrangThai, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpsbarTrangThai, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(29, 29, 29)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jlbSoLuongChunk))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jlbChunkDangTai))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jlbSoChunkHoanTat)
                    .addComponent(jLabel9))
                .addGap(23, 23, 23))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jtfDuongDanFileTorrent, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jbtMoFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGap(12, 12, 12))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfDuongDanFileTorrent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtMoFile))
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jbtMoFileHoanTat.setText("Mở file hoàn tất ");
        jbtMoFileHoanTat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtMoFileHoanTatActionPerformed(evt);
            }
        });

        jbtThoat.setText("Thoát");
        jbtThoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtThoatActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Chia sẻ file và chunks"));

        jbtnChiaSeChunk.setText("Duyệt...");
        jbtnChiaSeChunk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnChiaSeChunkActionPerformed(evt);
            }
        });

        jLabel4.setText("Đường dẫn file chunk :");

        jtfDuongDanFileChunk.setEnabled(false);

        jLabel6.setText("Đường dẫn file :");

        jtfDuongDanFile.setEnabled(false);

        jbtDuyetFileChiaSe.setText("Duyệt...");
        jbtDuyetFileChiaSe.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtDuyetFileChiaSeActionPerformed(evt);
            }
        });

        jLabel2.setText("Port:");

        jLabel8.setText("Giá trị port phải lớn hơn 1000");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jtfDuongDanFile, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtDuyetFileChiaSe))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jtfDuongDanFileChunk, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtnChiaSeChunk))
                            .addComponent(jLabel4))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfPortFile, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap())))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel8)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfPortFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfDuongDanFileChunk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnChiaSeChunk))
                .addGap(18, 18, 18)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtfDuongDanFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtDuyetFileChiaSe))
                .addContainerGap())
        );

        jMenu2.setText("File");
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        jMenuItem2.setText("Thêm torrent");
        jMenu2.add(jMenuItem2);

        jMenuItem3.setText("Thoát");
        jMenu2.add(jMenuItem3);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Options");

        jMenuItem4.setText("jMenuItem4");
        jMenu3.add(jMenuItem4);

        jMenuItem5.setText("jMenuItem5");
        jMenu3.add(jMenuItem5);

        jMenuBar1.add(jMenu3);

        jMenu4.setText("Help");

        jMenuItem6.setText("About");
        jMenu4.add(jMenuItem6);

        jMenuBar1.add(jMenu4);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbtMoFileHoanTat)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbtThoat, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtMoFileHoanTat)
                    .addComponent(jbtThoat))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
        // TODO add your handling code here:
        
        this.dispose();
    }//GEN-LAST:event_jMenu2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        // load file .map và broadcast thông tin đi
        logger.info("Begining download file ...");
        ArrayList<String> nodes=new ArrayList<>();// luu danh sach cac node
        // 
        File f=new File("."+"\\map\\nodes.map");
        if(!f.exists()){
            logger.info("Map file does not exists");
            return;
        }
        //System.out.print(f.getAbsolutePath()+"\n");
        //System.out.print(f.isFile());
        try{
           FileReader read=new FileReader(f);
           BufferedReader buf=new BufferedReader(read);
           String data="";
           while((data=buf.readLine())!=null){
               nodes.add(data);
           }
        }catch(IOException ex){
           Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
        // danh sach ip address va port cua cac may trong mang
        ArrayList<IP> ips=new ArrayList<IP>();
        String[] addcut=new String[2];// luu ipaddress va port
        String[] ipcut=new String[5];//luu cac octet
        for(int i=0;i<nodes.size();i++){
            addcut=nodes.get(i).split(" ");// cat string thanh ipaddr va port
            IP ip=new IP();
            ipcut=addcut[0].split("\\.");// lay cac octet trong ipaddr
            ip.setOctet1(Integer.parseInt(ipcut[0]));
            ip.setOctet2(Integer.parseInt(ipcut[1]));
            ip.setOctet3(Integer.parseInt(ipcut[2]));
            ip.setOctet4(Integer.parseInt(ipcut[3]));
            ip.setPort(Integer.parseInt(addcut[1]));
            
            ips.add(ip);// add vao list
        }
        
        // gui broadcast
        int time=0;
        while(time<hashes.size()){// gui broadcast va nhan tuan tu goi tin 
            String chunk=hashes.get(time);// lay gia tri hash trong hashes
            try {
                // tao UDPsocket
                DatagramSocket udpsocket=new DatagramSocket();
                // chuyen ma hash thanh mang byte
                byte[] brsend=chunk.getBytes();
                
                DatagramPacket pksend;
                DatagramPacket pkrecv;
                InetAddress ipclient;
                // duyet danh sach cac ip
                for(int i=0;i<ips.size();i++){
                    String ip=ips.get(i).getOctet1()+"."+ips.get(i).getOctet2()+"."+ips.get(i).getOctet3()+"."+ips.get(i).getOctet4();
                   byte oct1=(byte)ips.get(i).getOctet1();
                   byte oct2=(byte)ips.get(i).getOctet2();
                   byte oct3=(byte)ips.get(i).getOctet3();
                   byte oct4=(byte)ips.get(i).getOctet4();
                   byte[] byt=new byte[]{oct1,oct2,oct3,oct4};
                   
                  ipclient=InetAddress.getByAddress(ip, byt);
                   // gui hash cua chunk time qua cho may khac
                   pksend=new DatagramPacket(brsend,brsend.length,ipclient,ips.get(i).getPort());
                   
                   String mes=new String(pksend.getData(), 0, pksend.getLength());
                   // send broadcast 
                   logger.info("Send broadcast message to host "+ipclient.toString()+" value: "+mes);
                   udpsocket.send(pksend);
                   
                   byte[] rcvpkt=new byte[1024];
                   pkrecv=new DatagramPacket(rcvpkt, rcvpkt.length);
                   
                   new Thread(new ClientPeer(udpsocket, pkrecv, logger)).start();

                }
                // thuc hien download file tai may co chunk
                

            } catch (SocketException ex) {
                Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            }catch(IOException ex){
                ex.printStackTrace();
            }
            time++;
            System.out.println("---------------------------------------------------------------------------------------");
        }

        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jbtMoFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtMoFileActionPerformed
        // TODO add your handling code here:
        // mo file .torrent
        // luu thong tin hash file vào trong 1 mảng
        logger.info("Open torrent file to get infomation about needed file");
        jFileChooser1.showOpenDialog(null);
        File f=jFileChooser1.getSelectedFile();
        String duoi=f.getName();
        try {
            logger.info("Torrent file at "+f.getCanonicalPath());
        } catch (IOException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
        duoi=duoi.substring(duoi.lastIndexOf("."), duoi.length());
        System.out.println(duoi);
        if(!duoi.toLowerCase().equals(".torrent")){
            logger.info("File extendtion error");
            JOptionPane.showMessageDialog(this,"Sai tập tin!","Thông báo",JOptionPane.ERROR_MESSAGE);
            return;
        }
        jtfDuongDanFileTorrent.setText(jFileChooser1.getSelectedFile().getAbsolutePath());
        try {
            //int size=(int)f.length();
            //jlbKichThuocFile.setText(String.valueOf(size));
            // doc file
            FileReader read=new FileReader(f);
            String data="";
            BufferedReader buf=new BufferedReader(read);
            hashes=new ArrayList<>();
            logger.info("Begining reading file torrent");
            while((data=buf.readLine())!=null){
                hashes.add(data);
            }
            
        } catch (FileNotFoundException ex) {
            logger.info("File not found ");
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }catch(IOException ex){
            
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // set label sl chunk
        jlbSoLuongChunk.setText(String.valueOf(hashes.size()));
        int i=0;
        while(i<hashes.size()){
            System.out.println(hashes.get(i));
            i++;
        }
    }//GEN-LAST:event_jbtMoFileActionPerformed

    private void jbtThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtThoatActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jbtThoatActionPerformed

    private void jbtnChiaSeChunkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnChiaSeChunkActionPerformed
        // TODO add your handling code here:
        // load file .chunk len.
        // load danh sach cac file chunk len
         int port=1000;
        if(jtfPortFile.getText().equals("")){
            JOptionPane.showMessageDialog(this,"Không được bỏ trống port");
            return;
        }else{  
            port= Integer.parseInt(jtfPortFile.getText());
        
        }
        
        
        //jFileChooser1.showOpenDialog(null);
        jbtDuyetFileChiaSe.setEnabled(false);
        logger.info("Sharing chunk file");
        File f=null;
//      jFileChooser1.getSelectedFile();
        JFileChooser fcs=new JFileChooser();
        fcs.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fcs.showOpenDialog(this);
        f=fcs.getSelectedFile();
        ArrayList<String> hashshares=new ArrayList<String>();
        File[] fs=null;
        logger.info("Open directory "+f.getAbsolutePath());
        if(f.isDirectory()){
            fs=new File[f.listFiles().length];
            fs=f.listFiles();
        }/*else{
            fs=new File[1];
            fs[0]=f;
        }*/
        MessageDigest  md=null;
        try {
            md=MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            logger.info("MD5 hash error");
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // tinh toan hash 
        byte[] b=null;
        for(int i=0;i<fs.length;i++){
            try {
                b=Files.readAllBytes(fs[i].toPath());
                String hash=(new HexBinaryAdapter()).marshal(md.digest(b));
                hashshares.add(hash);
            } catch (IOException ex) {
                Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
        
         //        for(int i=0;i<hashshares.size();i++){
            //            System.out.println(hashshares.get(i));
            //        }
        // bat dau nhan va gui chunk 
       
        boolean close=true;
        int k=0;
        //int port =1000;
        try {
            while(close){
            
                // mo socket lang nghe broadcast 
                logger.info("Init socket at port "+port);
                DatagramSocket socket=new DatagramSocket(port);
                String stRcv;
                String stSend;
                byte[]rcvbuf=new byte[1024];
                DatagramPacket rcvpkt=new DatagramPacket(rcvbuf,rcvbuf.length);
                // nhan packet broadcast
                socket.receive(rcvpkt);
                stRcv=new String(rcvpkt.getData(), 0,rcvpkt.getLength());
                logger.info("Receive message "+stRcv);
                // duyet mang hash de so khop gia tri voi goi tin broadcast
                System.out.println("Co chunk nhận: "+stRcv);
                
                int j=0;
                for(int i=0;i<hashshares.size();i++){
                    if(hashshares.get(i).equals(stRcv)){// co giu chunk cua may yeu cau 
                       j=i;
                       stSend="got";
                       byte[] sendbuf=new byte[1024];
                       sendbuf=stSend.getBytes();
                       DatagramPacket sendpkt=new DatagramPacket(sendbuf,sendbuf.length,rcvpkt.getAddress(),rcvpkt.getPort());
                       // gui thong diep "got" cho may yeu cau
                       logger.info("Send to host "+rcvpkt.getAddress().toString()+"message "+stSend);
                       socket.send(sendpkt);
                       // nhan thong diep "please send"
                       System.out.println("Co chunk GửI:"+stSend);
                       
                       break;
                       
                    }    
                }
                
                if(k==5){
                    break;
                }
                
                k++;
                    //break;
                    
            }        
                    
                    
                    // neu goi tin nhan duoc co data trung voi gia tri hash 
                    // cat thanh cac manh 1024 byte
                    // truyen cac manh nay qua cho may yeu cau
        } catch (SocketException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jbtnChiaSeChunkActionPerformed

    private void jbtMoFileHoanTatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtMoFileHoanTatActionPerformed
        // TODO add your handling code here:
//        String ad="192.168.1.1";
//        String[] a;
//        a=ad.split("\\.");
//        for(int i=0;i<a.length;i++){
//            System.out.println(a[i]);
//        }
    }//GEN-LAST:event_jbtMoFileHoanTatActionPerformed

    private void jbtDuyetFileChiaSeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtDuyetFileChiaSeActionPerformed
       int port=1000;
        if(jtfPortFile.getText().equals("")){
            JOptionPane.showMessageDialog(this,"Không được bỏ trống port");
            return;
        }else{  
            port= Integer.parseInt(jtfPortFile.getText());
        
        }
        
        FileReader read = null;
        try {
            // TODO add your handling code here:
            jbtnChiaSeChunk.setEnabled(false);
            OpenFile();
            int CHUNK_SIZE=524288;
            readAndFragment(jtfDuongDanFile.getText(), CHUNK_SIZE);
            File file=new File(torrentName);
            read = new FileReader(file);
            String data="";
            BufferedReader buf=new BufferedReader(read);
            ArrayList<String> hashes=new ArrayList<>();
            logger.info("Begining reading file torrent");
            while((data=buf.readLine())!=null){
                hashes.add(data);
            }
            // chia se file
            
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                read.close();
            } catch (IOException ex) {
                Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        
        
    }//GEN-LAST:event_jbtDuyetFileChiaSeActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Mainform().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton jbtDuyetFileChiaSe;
    private javax.swing.JButton jbtMoFile;
    private javax.swing.JButton jbtMoFileHoanTat;
    private javax.swing.JButton jbtThoat;
    private javax.swing.JButton jbtnChiaSeChunk;
    private javax.swing.JLabel jlbChunkDangTai;
    private javax.swing.JLabel jlbSoChunkHoanTat;
    private javax.swing.JLabel jlbSoLuongChunk;
    private javax.swing.JProgressBar jpsbarTrangThai;
    private javax.swing.JTextField jtfDuongDanFile;
    private javax.swing.JTextField jtfDuongDanFileChunk;
    private javax.swing.JTextField jtfDuongDanFileTorrent;
    private javax.swing.JTextField jtfPortFile;
    // End of variables declaration//GEN-END:variables
}
